package com.molichuxing.services.infrastructure.service.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.utils.ObjectCastUtil;
import com.molichuxing.services.infrastructure.bean.AdvertBean;
import com.molichuxing.services.infrastructure.convertor.Convert;
import com.molichuxing.services.infrastructure.dao.AdvertMapper;
import com.molichuxing.services.infrastructure.dto.request.create.AdvertCreateDto;
import com.molichuxing.services.infrastructure.dto.response.AdvertDto;
import com.molichuxing.services.infrastructure.service.AdvertService;
import com.molichuxing.services.property.AdvertPositionEnum;

@Service("AdvertService")
public class AdvertServiceImpl implements AdvertService{

	@Autowired
	private AdvertMapper advertMapper;
	
	/**
	 * 获取广告列表
	 * 
	 * @param map
	 *            参数
	 *key:name
	 *            String 广告名称 非必填
	 *key:position
	 *            Integer 广告位置（1:终端屏保广告   2:APP开机广告） 非必填
	 *key:startTime
	 *            String 请求开始时间 非必填
	 *key:endTime
	 *            String 请求结束时间 非必填
	 *key:pageNum
	 *            Integer 当前页
	 *key:pageSize
	 *            Integer 每页显示条数
	 * @return
	 */
	@Override
	public Paged<AdvertDto> getAdvertList(Map<String, Object> map) {
		// 查询总条数
		long total = advertMapper.getAdvertListCount(map);
		if(total <= 0) {
			return null;
		}
		
		/*分页查询集合*/ 
		Integer pageNum = ObjectCastUtil.castInteger(map.get("pageNum"));
		Integer pageSize = ObjectCastUtil.castInteger(map.get("pageSize"));       
		List<AdvertBean>  list =  advertMapper.getAdvertList(map,pageNum,pageSize);
		List<AdvertDto> dtoList = Convert.toAdvertDto(list);
		Paged<AdvertDto> paged = new Paged<>(dtoList, total,pageSize);
		return paged;			
	}
	
	/**
	 * 根据广告id获取广告信息
	 * @param id
	 * @return
	 */
	@Override
	public AdvertDto getAdvertById(Integer id) {
		AdvertBean bean = advertMapper.getById(id);
		return Convert.toAdvertDto(bean);
	}
	
	/**
	 * 新增广告信息
	 * @param createDto
	 * @return
	 */
	@Override
	public Integer create(AdvertCreateDto createDto) {
		AdvertBean bean = advertMapper.getAdvertByName(createDto.getName());
		if(null != bean) {
			throw new BizException(101, "广告名称已存在");
		}
		//app开机广告 只允许有一条（新增覆盖掉老数据）
		if(AdvertPositionEnum.APP.getValue().equals(createDto.getPosition())) {
			advertMapper.deleteByPosition(createDto.getPosition());
		}
		bean = new AdvertBean();
		BeanUtils.copyProperties(createDto, bean);
		bean.setIsDelete(false);
		advertMapper.create(bean);
		return bean.getId();
	}
	
	
}
